<template>
    <div class="container-fluid" style="background: #fff">
        <div class="row page-title">
            <div class="col-xs-11">
                <h1>首页广告</h1>
            </div>
            <div class="col-xs-1">
                <a title="添加"  @click="dialogFormVisible = true">
                    <el-tooltip content="添加" placement="top">
                        <i class="el-icon-plus"></i>
                    </el-tooltip>
                </a>
            </div>
        </div>
        
        <el-col :span="24" class="table-bottom-margin">
            <el-table :data="tableData" border style="width: 100%" :header-cell-class-name="headerbg">
                <el-table-column  label="图片链接">
                    <template slot-scope="scope">
                        <a :href="scope.row.ShowImage" target="_blank">
                            <img :src="scope.row.ShowImage" class="image" style="width:50px;height:50px">
                        </a>
                    </template>
                </el-table-column>
                <!-- LinkUrl -->
                <el-table-column prop="Title" label="跳转位置"> </el-table-column>
                <el-table-column prop="SortNo" label="顺序"> </el-table-column>
                <el-table-column prop="AddTime" label="创建时间" :formatter="DateFormatter"> </el-table-column>
                <el-table-column label="操作" align="center" min-width="40" width="250px">
                    <template slot-scope="scope">
                        <el-tooltip content="前移" placement="top">
                            <i class="fa fa-arrow-left el-text-yellow" @click="order(scope.row.Id,(Number(scope.row.SortNo)-1))"></i>
                        </el-tooltip>&nbsp;&nbsp;&nbsp;&nbsp;
                        <el-tooltip content="后移" placement="top">
                            <i class="fa fa-arrow-right el-text-yellow" @click="order(scope.row.Id,(Number(scope.row.SortNo)+1))"></i>
                        </el-tooltip>&nbsp;&nbsp;&nbsp;&nbsp;
                        <el-tooltip content="进入视频" placement="top">
                            <i class="fa fa-edit el-text-blue" @click="Edit(scope.row)"></i>
                        </el-tooltip>&nbsp;&nbsp;&nbsp;&nbsp;
                        <el-tooltip content="删除" placement="top">
                            <i class="fa fa-trash el-text-danger" @click="del(scope.row.Id)"></i>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>    
        </el-col>
        <el-col :sapn="24" style="text-align:right" v-if="count>0">
            <el-pagination @size-change="pageSizeChange" @current-change="pageCurrentChange" :current-page="currentPage"
                :page-sizes="[10]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="count">
            </el-pagination>
        </el-col>
        <br/>
        <!--添加/编辑-->
        <el-dialog title="新增首页广告" :visible.sync="dialogFormVisible">
            <el-form :model="form" ref="form" :rules="rules">
                <el-form-item class="hr" :label-width="formLabelWidth"></el-form-item>
                <!-- ShowImage 图片链接 (720*400) https://jsonplaceholder.typicode.com/posts/-->
                <el-form-item label="上传图片：" prop="ShowImage" :label-width="formLabelWidth">
                    <el-upload
                        class="avatar-uploader"
                        :action="uploadUrl"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                    <i class="el-text-danger el-icon-circle-close" v-if="!imageUrl"></i>
                    <span v-if="imageUrl">上传成功&nbsp;&nbsp;&nbsp;&nbsp;<i class="text-success el-icon-circle-check"></i></span>
                </el-form-item>
                <el-form-item label="跳转外链：" prop="LinkUrl" :label-width="formLabelWidth">
                    <el-input v-model="form.LinkUrl" placeholder="请输入http外链" style="width:60%;"></el-input>
                </el-form-item>
                 <el-form-item label="跳转位置：" prop="VideoId" :label-width="formLabelWidth">
                    <!-- <el-select v-model="form.VideoId" placeholder="请选择" clearable style="width:60%;">
                        <el-option label="区域一" value="shanghai"></el-option>
                    </el-select> -->
                    <el-select v-model="form.VideoId" filterable remote reserve-keyword placeholder="请输入关键词" :remote-method="remoteMethod" :loading="loading" clearable style="width:60%;">
                        <el-option v-for="item in searchedSelectList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="展示顺序：" prop="SortNo" :label-width="formLabelWidth">
                    <el-input v-model.number="form.SortNo" type="number" placeholder="输入数字，数字越小越展示优先" style="width:60%;"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="save" size="medium">确 定</el-button>
                <el-button @click="dialogFormVisible = false" size="medium">取 消</el-button>
            </div>
      </el-dialog>
    </div>
</template>

<script>
    export default {
        data(){
            return{
                currentPage:1,
                pageSize:10,
                count:0,
                headerbg:'headerbg',//表格头部背景色
                dialogFormVisible: false,
                formLabelWidth: '25%',
                tableData:[],
                form: {},
                rules:{
                    LinkUrl:[
                        { required: true, message: '请输入跳转外链', trigger: 'blur' },
                    ],
                    VideoId:[
                        { required: true, message: '请选择跳转位置', trigger: 'change' }
                    ],
                    SortNo:[
                        { required: true, message: '请输入展示顺序'},
                        { type: 'number', message: '顺序必须为小于51的正整数', min:0 ,max:50}
                    ]
                },
                getListUrl:this.urlConfig+'/api/AdvertInfo/GetAdverList',
                delUrl:this.urlConfig+'/api/AdvertInfo/PostDeleteAdverById',
                editUrl:this.urlConfig+'/api/AdvertInfo/PostAdverBySortNo',
                addUrl:this.urlConfig+'/api/AdvertInfo/PostAdver',
                uploadUrl:this.urlConfig+'/api/AdvertInfo/PostImgUpload/',
                DropDownListUrl:this.urlConfig+'/api/AdvertInfo/GetVideoDropList',

                searchedSelectList: [],
                dropDownList: [],
                loading: false,

                imageUrl: ''
            }
        },
        components: {
        },
        mounted() {
            this.getList(10,this.currentPage);
            this.getDropDownList();
        },
        methods:{
            handleAvatarSuccess(res, file) {
                if(res["Code"] == "200") {
                    this.form.ShowImage = this.urlConfig+res.ImgUrl;
                }
                this.imageUrl = URL.createObjectURL(file.raw);
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            remoteMethod(query) {
                if (query !== '') {
                    this.loading = true;
                    setTimeout(() => {
                        this.loading = false;
                        this.searchedSelectList = this.dropDownList.filter(item => {
                            return item.label.indexOf(query) > -1;
                        });
                    }, 200);
                } else {
                    this.searchedSelectList = [];
                }
            },
            getDropDownList:function(){
                this.$http.get(this.DropDownListUrl,{
                    emulateJSON:true
                }).then(function(res){
                    if(res.body["Code"] == "200") {
                        this.dropDownList = JSON.parse(res.body.Data);
                        this.searchedSelectList = this.dropDownList;
                    }
                });
            },
            DateFormatter:function(row){
                return (!row.AddTime)?'':moment(row.AddTime).format("YYYY-MM-DD");
            },
            getList:function(PageSize,PageIndex){
                this.$http.get(this.getListUrl+'?PageSize='+PageSize+'&PageIndex='+PageIndex,{
                    emulateJSON:true
                }).then(function(res){
                    this.count = 0;
                    this.tableData = [];
                    if(res.body["Code"] == "200") {
                        this.count = res.body.Count;
                        this.tableData = JSON.parse(res.body.Advertinfo);
                    }
                });
            },
            Edit:function(row){
                //跳转多视频页面 this.$route.query.id
                this.$router.push({ path: row.LinkUrl ,query: { id: row.VideoId} });
            },
            del:function(id){
                this.$confirm('确定需要删除该记录?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$http.post(this.delUrl+'?Id='+id,{
                        emulateJSON:true
                    }).then(function(res){
                        if(res.body["Code"] == "200") {
                            this.getList(10,this.currentPage);
                            this.$notify({title: '成功',message: '删除成功！',type: 'success'});
                        }else{
                            this.$notify({title: '警告',message: res.body["Message"],type: 'warning',duration:1200});
                        }
                    });
                }).catch(() => {});
            },
            order:function(Id,order){
                this.$http.post(this.editUrl,{Id:Id,SortNo:order},{
                    emulateJSON: true
                }).then(function(res) {
                    console.log(res,'res');
                    if(res.body["Code"] == "200") {
                        this.getList(10,this.currentPage);
                    }else{
                        this.$notify.error({title: '错误',message:res.body["Message"]});
                    }
                });
            },
            validateFun:function(){
                var errorInfo='';
                for(var i=0;i<3;i++){
                    this.$refs.form.validateField((['LinkUrl','VideoId','SortNo'][i]),(re)=>{
                        errorInfo+=re+(re==''?'':', ');
                    })
                }
                return errorInfo;
            },
            save:function(){
                var errorInfo=this.validateFun();
                if(!errorInfo){
                    this.$http.post(this.addUrl,this.form,{
                        emulateJSON: true
                    }).then(function(res) {
                        if(res.body["Code"] == "200") {
                            this.dialogFormVisible = false;
                            this.getList(10,this.currentPage);
                        }else{
                            this.$notify.error({title: '错误',message:res.body["Message"]});
                        }
                    });
                }else{
                    this.$notify({title: '警告',message: errorInfo,type: 'warning',duration:1200});
                    return false;
                }
            },
            pageSizeChange:function(val){
                this.pageSize = val;
                this.getList(val,this.currentPage);
            },
            pageCurrentChange:function(val){
                this.currentPage = val;
                this.getList(this.pageSize,val);
            }
        }
    }
</script>
<style>
    .headerbg{
        background-color: #f4f3f3 !important;
    }

    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
    input[type="file"]{
        display: none;
    }
    .text-success,.text-danger{
        font-size: large;
    }
</style>
